﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Dynamic;
using Microsoft.AspNetCore.Authorization;

namespace ApiCoreProject.Api.Controllers
{
	[Authorize]
	[Route("api/[controller]")]
	[ApiController]
	public class PaymentController : ControllerBase
	{
        public IConfiguration Configuration { get; }

        public PaymentController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        [Route("~/api/pay")]
		[HttpPost]
		public JsonResult Post([FromBody]PayParams value)
		{
			//var json = new JObject();

			dynamic d = new ExpandoObject();
			value.orderId = string.IsNullOrWhiteSpace(value.orderId) ? Tools.GetRandCode() : value.orderId;
			try
			{
				var dic = new Dictionary<string, string>
					{
						{"version", "1.1"},
						{"lang", "zh-cn"},
						{"plugins", "test-001"},
						{"appid", Configuration["HPJ:AppID"]},//appid
	                    {"appsecret",Configuration["HPJ:AppSecret"]},//appsecret

						{"trade_order_id", value.orderId},//订单号
	                    {"payment",value.paymentType},//支付类型
	                    {"total_fee", value.money},//金额
	                    {"title", value.title},//标题，只能数据字或英文（中文乱码，找不到原因）
	                    {"time", Tools.GenerateTimeStamp().ToString()},//时间戳
	                    {"notify_url", value.notify_url},//通知链接
	                    {"return_url", value.return_url},//跳转链接
	                    {"nonce_str", Tools.GetRandCode(32)},//随机字符串
	                };

				dic.Add("hash", HttpPostHelper.Sign(dic, Configuration["HPJ:AppSecret"]));

				var sr = JsonConvert.DeserializeObject<SamplesResult>(HttpPostHelper.PostHttp(dic));
				//json.Add(new JProperty("openid", sr.Openid));
				//json.Add(new JProperty("url", sr.Url));
				//json.Add(new JProperty("errcode", sr.Errcode));
				//json.Add(new JProperty("errmsg", sr.Errmsg));
				//json.Add(new JProperty("hash", sr.Hash));

				d.openid = sr.Openid;
				d.url = sr.Url;
				d.errcode = sr.Errcode;
				d.errmsg = sr.Errmsg;
				d.hash = sr.Hash;

			}
			catch (Exception ex)
			{
				
				throw ex;
			}

			return new JsonResult(new { code=1,msg="OK",data= d });// (json.ToString());
		}


		[Route("~/api/Notify")]
		[HttpPost]
		public string NotifyUrl()
		{
			var context = HttpContext;
			var tradeOrderId = context.Request.Form["trade_order_id"];
			var totalFee = context.Request.Form["total_fee"];
			var transactionId = context.Request.Form["transaction_id"];
			var plugins = context.Request.Form["plugins"];
			var status = context.Request.Form["status"];
			var hash = context.Request.Form["hash"];
			//写修改订单表
			return (!string.IsNullOrEmpty(tradeOrderId) ? "success" : "");
		}

		
	}

	public class HttpPostHelper {

		public static string PostHttp(Dictionary<string, string> dicArray)
		{
			string result;
			try
			{
				var req = (HttpWebRequest)WebRequest.Create("https://api.xunhupay.com/payment/do.html");
				req.KeepAlive = false;
				req.Method = "POST";
				req.ContentType = "application/x-www-form-urlencoded";
				req.Accept = "application/json";

				var paramData = ParamData(dicArray);
				var data = Encoding.Default.GetBytes(paramData);

				req.ContentLength = data.Length;

				var swrite = req.GetRequestStream();
				swrite.Write(data, 0, data.Length);
				swrite.Close();

				var resp = (HttpWebResponse)req.GetResponse();
				var stream = resp.GetResponseStream();

				//获取响应内容
				var reader = new StreamReader(stream ?? throw new InvalidOperationException(), Encoding.UTF8);
				result = reader.ReadToEnd();
			}
			catch (WebException ex)
			{
				result = ex.Message;
			}

			return result;
		}

		public static string Sign(Dictionary<string, string> dicArray,string appSecret)
		{
			var prestr = new StringBuilder();
			foreach (var temp in dicArray.OrderBy(o => o.Key))
			{
				prestr.Append(temp.Key + "=" + temp.Value + "&");
			}
			//Configuration["HPJ:AppSecret"]
			var nLen = prestr.Length;
			prestr.Remove(nLen - 1, 1);
			var signValue = Tools.Md5(prestr + appSecret);
			return signValue;
		}

		public static string ParamData(Dictionary<string, string> dicArray)
		{
			var prestr = new StringBuilder();
			foreach (var temp in dicArray)
			{
				prestr.Append(temp.Key + "=" + temp.Value + "&");
			}

			var nLen = prestr.Length;
			prestr.Remove(nLen - 1, 1);

			return prestr.ToString();
		}

	}

	public class PayParams
	{
		public string paymentType { get; set; }
		public string money { get; set; }

		public string title { get; set; }
		public string orderId { get; set; }
		public string notify_url { get; set; }
		public string return_url { get; set; }
	}
	public class SamplesResult
	{
		public string Openid { get; set; }

		public string Url { get; set; }

		public string Errcode { get; set; }

		public string Errmsg { get; set; }

		public string Hash { get; set; }
	}
}
